// 任务管理页面 - Bootstrap风格JavaScript

// 全局变量
let currentTaskId = null;
let selectedTasks = new Set();
let currentPage = 1;
let totalPages = 1;
let isLoading = false;
let allRequirements = [];
let allDevelopers = [];
let requirementsMap = new Map();

// DOM元素
const elements = {
    taskTable: null,
    taskDetailOffcanvas: null,
    taskEditOffcanvas: null,
    batchModal: null,
    searchInput: null,
    filterForm: null,
    taskForm: null,
    batchForm: null
};

// Bootstrap组件实例
const bsComponents = {
    taskDetailOffcanvas: null,
    taskEditOffcanvas: null,
    batchModal: null
};

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeElements();
    initializeBootstrapComponents();
    initializeEventListeners();
    loadInitialData();
});

// 加载初始数据
function loadInitialData() {
    console.log('开始加载初始数据');
    Promise.all([
        loadRequirementsAsync(),
        loadDevelopersAsync()
    ]).then(() => {
        console.log('需求和开发者数据加载完成，开始加载任务');
        loadTasks();
    }).catch(error => {
        console.error('加载初始数据失败:', error);
        console.log('即使加载失败也要加载任务列表');
        loadTasks(); // 即使加载失败也要加载任务列表
    });
}

// 初始化DOM元素
function initializeElements() {
    elements.taskTable = document.getElementById('taskTable');
    elements.taskDetailOffcanvas = document.getElementById('taskDetailPanel');
    elements.taskEditOffcanvas = document.getElementById('taskEditOffcanvas');
    elements.batchModal = document.getElementById('batchModal');
    elements.searchInput = document.getElementById('searchInput');
    elements.filterForm = document.getElementById('filterForm');
    elements.taskForm = document.getElementById('taskForm');
    elements.batchForm = document.getElementById('batchForm');
    
    console.log('Elements initialized:', {
        taskTable: !!elements.taskTable,
        taskDetailOffcanvas: !!elements.taskDetailOffcanvas,
        taskEditOffcanvas: !!elements.taskEditOffcanvas,
        searchInput: !!elements.searchInput,
        filterForm: !!elements.filterForm
    });
    
    // 检查关键元素是否存在
    if (!elements.taskDetailOffcanvas) {
        console.error('taskDetailOffcanvas element not found!');
    }
    if (!elements.taskEditOffcanvas) {
        console.error('taskEditOffcanvas element not found!');
    }
    if (!elements.taskTable) {
        console.error('taskTable element not found!');
    }
}

// 初始化Bootstrap组件
function initializeBootstrapComponents() {
    if (elements.taskDetailOffcanvas) {
        bsComponents.taskDetailOffcanvas = new bootstrap.Offcanvas(elements.taskDetailOffcanvas);
    }
    if (elements.taskEditOffcanvas) {
        bsComponents.taskEditOffcanvas = new bootstrap.Offcanvas(elements.taskEditOffcanvas);
    }
    if (elements.batchModal) {
        bsComponents.batchModal = new bootstrap.Modal(elements.batchModal);
    }
}

// 初始化事件监听器
function initializeEventListeners() {
    // 搜索输入
    if (elements.searchInput) {
        let searchTimeout;
        elements.searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                currentPage = 1;
                loadTasks();
            }, 300);
        });
    }

    // 筛选表单
    if (elements.filterForm) {
        elements.filterForm.addEventListener('change', function() {
            currentPage = 1;
            loadTasks();
        });
    }

    // 绑定筛选事件
    const statusFilter = document.getElementById('statusFilter');
    const priorityFilter = document.getElementById('priorityFilter');
    const requirementFilter = document.getElementById('requirementFilter');
    const assigneeFilter = document.getElementById('assigneeFilter');
    const applyFiltersBtn = document.getElementById('applyFilterBtn');
    const resetFilterBtn = document.getElementById('resetFilterBtn');
    
    if (statusFilter) statusFilter.addEventListener('change', loadTasks);
    if (priorityFilter) priorityFilter.addEventListener('change', loadTasks);
    if (requirementFilter) requirementFilter.addEventListener('change', loadTasks);
    if (assigneeFilter) assigneeFilter.addEventListener('change', loadTasks);
    if (applyFiltersBtn) applyFiltersBtn.addEventListener('click', loadTasks);
    if (resetFilterBtn) resetFilterBtn.addEventListener('click', resetFilters);

    // 任务表单提交
    if (elements.taskForm) {
        elements.taskForm.addEventListener('submit', handleTaskSubmit);
    }

    // 批量操作表单提交
    if (elements.batchForm) {
        elements.batchForm.addEventListener('submit', handleBatchSubmit);
    }

    // 全选复选框
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', handleSelectAll);
    }

    // 新建任务按钮
    const newTaskBtn = document.getElementById('newTaskBtn');
    if (newTaskBtn) {
        newTaskBtn.addEventListener('click', () => openTaskModal());
    }
    
    // 详情面板编辑按钮
    const editDetailBtn = document.getElementById('editDetailBtn');
    if (editDetailBtn) {
        editDetailBtn.addEventListener('click', () => {
            if (currentTaskId) {
                editTask(currentTaskId);
                // 关闭详情面板
                if (bsComponents.taskDetailOffcanvas) {
                    bsComponents.taskDetailOffcanvas.hide();
                }
            }
        });
    }

    // 批量操作按钮已移除

    // 批量操作选项
    document.addEventListener('click', function(e) {
        if (e.target.matches('.batch-action-btn')) {
            const action = e.target.dataset.action;
            showBatchForm(action);
        }
    });

    // 表格行点击事件
    if (elements.taskTable) {
        elements.taskTable.addEventListener('click', handleTableClick);
    }
    
    // 任务状态变化时自动调整进度
    const taskStatusSelect = document.getElementById('taskStatus');
    const taskProgressInput = document.getElementById('taskProgress');
    
    if (taskStatusSelect && taskProgressInput) {
        taskStatusSelect.addEventListener('change', function() {
            const status = this.value;
            const currentProgress = parseInt(taskProgressInput.value) || 0;
            
            // 根据状态自动设置进度并显示提示
            if (status === 'TODO') {
                if (currentProgress !== 0) {
                    taskProgressInput.value = 0;
                    showToast('TODO状态的任务进度已自动设置为0%', 'info');
                }
                taskProgressInput.disabled = true;
            } else if (status === 'COMPLETED') {
                if (currentProgress !== 100) {
                    taskProgressInput.value = 100;
                    showToast('COMPLETED状态的任务进度已自动设置为100%', 'info');
                }
                taskProgressInput.disabled = true;
            } else {
                // 其他状态允许手动输入进度
                taskProgressInput.disabled = false;
                if (currentProgress === 0 && status === 'IN_PROGRESS') {
                    // 如果从TODO切换到IN_PROGRESS，建议设置一个合理的初始进度
                    taskProgressInput.value = 10;
                    showToast('已为进行中的任务设置初始进度10%，您可以手动调整', 'info');
                }
            }
        });
        
        // 页面加载时也检查一次状态
        const initialStatus = taskStatusSelect.value;
        if (initialStatus === 'TODO' || initialStatus === 'COMPLETED') {
            taskProgressInput.disabled = true;
        }
    }

}

// 处理表格点击事件
function handleTableClick(e) {
    const target = e.target;
    const row = target.closest('tr');
    
    if (!row || !row.dataset.taskId) return;
    
    const taskId = parseInt(row.dataset.taskId);
    
    // 复选框点击
    if (target.type === 'checkbox' && target.classList.contains('task-checkbox')) {
        handleTaskSelect(taskId, target.checked);
        return;
    }
    
    // 操作按钮点击
    if (target.matches('.btn')) {
        e.stopPropagation();
        const action = target.dataset.action;
        
        switch (action) {
            case 'view':
                viewTask(taskId);
                break;
            case 'edit':
                editTask(taskId);
                break;
            case 'delete':
                deleteTask(taskId);
                break;
        }
        return;
    }
    
    // 行点击 - 查看详情
    if (!target.matches('input, button, .btn')) {
        viewTask(taskId);
    }
}

// 加载任务列表
async function loadTasks() {
    if (isLoading) return;
    
    isLoading = true;
    showLoading(true);
    
    try {
        const params = new URLSearchParams({
            page: currentPage - 1, // Spring Boot分页从0开始
            size: 20,
            sortField: 'requirement',
            sortDirection: 'asc',
            title: elements.searchInput?.value || '',
            status: document.getElementById('statusFilter')?.value || '',
            priority: document.getElementById('priorityFilter')?.value || '',
            requirement: document.getElementById('requirementFilter')?.value || '',
            assignee: document.getElementById('assigneeFilter')?.value || ''
        });
        
        console.log('正在加载任务，参数:', params.toString());
        const response = await fetch(`/api/tasks?${params}`);
        console.log('API响应状态:', response.status);
        
        if (!response.ok) throw new Error(`加载任务失败: ${response.status}`);
        
        const data = await response.json();
        console.log('API返回数据:', data);
        
        renderTasks(data.content || data);
        updatePagination(data);
        updateTaskCount(data.totalElements || 0);
        
    } catch (error) {
        console.error('加载任务失败:', error);
        showToast('加载任务失败: ' + error.message, 'error');
    } finally {
        isLoading = false;
        showLoading(false);
    }
}

// 渲染任务列表
function renderTasks(tasks) {
    const tbody = elements.taskTable?.querySelector('tbody');
    if (!tbody) return;
    
    if (tasks.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="text-center py-5">
                    <i class="bi bi-clipboard-x fs-1 text-muted d-block mb-3"></i>
                    <h5 class="text-muted">暂无任务</h5>
                    <p class="text-muted mb-3">还没有创建任何任务，点击下方按钮开始创建</p>
                    <button type="button" class="btn btn-primary" onclick="openTaskModal()">
                        <i class="bi bi-plus-circle me-1"></i>新建任务
                    </button>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = tasks.map(task => renderTaskRow(task)).join('');
    updateSelectAllState();
}

// 渲染单个任务行
function renderTaskRow(task) {
    const isSelected = selectedTasks.has(task.id);
    const isSubtask = task.parentId;
    
    // 根据任务层级计算缩进、图标和样式类
    let indentClass = '';
    let levelIcon = '';
    let rowLevelClass = '';
    let titleLevelClass = '';
    
    if (task.level) {
        switch (task.level) {
            case 'LEVEL_1':
                indentClass = 'task-level-1';
                levelIcon = '';
                rowLevelClass = 'task-row-level-1';
                titleLevelClass = 'task-title-level-1';
                break;
            case 'LEVEL_2':
                indentClass = 'task-level-2';
                levelIcon = '';
                rowLevelClass = 'task-row-level-2';
                titleLevelClass = 'task-title-level-2';
                break;
            case 'LEVEL_3':
                indentClass = 'task-level-3';
                levelIcon = '';
                rowLevelClass = 'task-row-level-3';
                titleLevelClass = 'task-title-level-3';
                break;
        }
    } else if (isSubtask) {
        // 兼容旧的逻辑，如果没有level字段但有parentId
        indentClass = 'task-level-2';
        levelIcon = '';
        rowLevelClass = 'task-row-level-2';
        titleLevelClass = 'task-title-level-2';
    } else {
        // 默认为一级任务
        indentClass = 'task-level-1';
        rowLevelClass = 'task-row-level-1';
        titleLevelClass = 'task-title-level-1';
    }
    
    return `
        <tr data-task-id="${task.id}" class="${isSelected ? 'table-active' : ''} ${rowLevelClass}">
            <td>
                <div class="form-check">
                    <input class="form-check-input task-checkbox" type="checkbox" 
                           ${isSelected ? 'checked' : ''} data-task-id="${task.id}">
                </div>
            </td>
            <td>
                <span class="badge bg-light text-dark">#${task.id}</span>
            </td>
            <td>
                <div class="${indentClass}">
                    ${levelIcon}
                    <span class="${titleLevelClass}">${escapeHtml(task.title)}</span>
                </div>
            </td>
            <td class="text-center">
                ${task.requirementId ? `
                    <span class="badge bg-secondary text-white">
                        <i class="bi bi-file-text me-1"></i>
                        ${escapeHtml(task.requirementTitle || getRequirementDisplayName(task.requirementId))}
                    </span>
                ` : '<span class="text-muted">无需求</span>'}
            </td>
            <td class="text-center">
                <span class="badge ${getStatusBadgeClass(task.status)}">
                    ${getStatusText(task.status)}
                </span>
            </td>
            <td class="text-center">
                <span class="priority-badge priority-${task.priority?.toLowerCase() || 'medium'}">
                    ${getPriorityText(task.priority)}
                </span>
            </td>
            <td class="text-center">
                ${task.assigneeId ? `
                    <div class="d-flex align-items-center justify-content-center">
                        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" 
                             style="width: 24px; height: 24px; font-size: 10px;">
                            ${getDeveloperDisplayName(task.assigneeId).charAt(0).toUpperCase()}
                        </div>
                        <small>${escapeHtml(getDeveloperDisplayName(task.assigneeId))}</small>
                    </div>
                ` : '<span class="text-muted">未分配</span>'}
            </td>
            <td class="text-center">
                <div class="d-flex align-items-center justify-content-center">
                    <div class="progress flex-grow-1 me-2" style="height: 6px;">
                        <div class="progress-bar" role="progressbar" 
                             style="width: ${task.progress || 0}%" 
                             aria-valuenow="${task.progress || 0}" 
                             aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                    <small class="text-muted">${task.progress || 0}%</small>
                </div>
            </td>
            <td>
                <div class="btn-group btn-group-sm" role="group">
                    <button type="button" class="btn btn-outline-primary" 
                            data-action="view" title="查看详情">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button type="button" class="btn btn-outline-secondary" 
                            data-action="edit" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button type="button" class="btn btn-outline-danger" 
                            data-action="delete" title="删除">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </td>
        </tr>
    `;
}

// 获取状态徽章样式
function getStatusBadgeClass(status) {
    const classes = {
        'TODO': 'bg-secondary',
        'IN_PROGRESS': 'bg-primary',
        'PENDING_REVIEW': 'bg-warning',
        'COMPLETED': 'bg-success',
        'BLOCKED': 'bg-danger',
        'PAUSED': 'bg-info',
        'CANCELLED': 'bg-dark'
    };
    return classes[status] || 'bg-secondary';
}

// 获取状态文本
function getStatusText(status) {
    const texts = {
        'TODO': '待办',
        'IN_PROGRESS': '进行中',
        'PENDING_REVIEW': '待审核',
        'COMPLETED': '已完成',
        'BLOCKED': '阻塞',
        'PAUSED': '暂停',
        'CANCELLED': '已取消'
    };
    return texts[status] || status;
}

// 获取优先级徽章样式
function getPriorityBadgeClass(priority) {
    const classes = {
        'URGENT': 'bg-danger text-white',
        'HIGH': 'bg-warning',
        'MEDIUM': 'bg-info',
        'LOW': 'bg-success'
    };
    return classes[priority] || 'bg-secondary';
}

// 获取优先级图标
function getPriorityIcon(priority) {
    const icons = {
        'URGENT': 'bi-exclamation-triangle-fill',
        'HIGH': 'bi-arrow-up',
        'MEDIUM': 'bi-dash',
        'LOW': 'bi-arrow-down'
    };
    return icons[priority] || 'bi-dash';
}

// 获取优先级文本
function getPriorityText(priority) {
    const texts = {
        'LOW': '低',
        'MEDIUM': '中',
        'HIGH': '高',
        'URGENT': '紧急'
    };
    return texts[priority] || priority;
}

// 处理任务选择
function handleTaskSelect(taskId, checked) {
    if (checked) {
        selectedTasks.add(taskId);
    } else {
        selectedTasks.delete(taskId);
    }
    
    updateTaskRowSelection(taskId, checked);
    updateSelectAllState();
    updateBatchActionButton();
}

// 处理全选
function handleSelectAll(e) {
    const checked = e.target.checked;
    const checkboxes = document.querySelectorAll('.task-checkbox');
    
    checkboxes.forEach(checkbox => {
        const taskId = parseInt(checkbox.dataset.taskId);
        checkbox.checked = checked;
        
        if (checked) {
            selectedTasks.add(taskId);
        } else {
            selectedTasks.delete(taskId);
        }
        
        updateTaskRowSelection(taskId, checked);
    });
    
    updateBatchActionButton();
}

// 更新任务行选中状态
function updateTaskRowSelection(taskId, selected) {
    const row = document.querySelector(`tr[data-task-id="${taskId}"]`);
    if (row) {
        row.classList.toggle('table-active', selected);
    }
}

// 更新全选状态
function updateSelectAllState() {
    const selectAllCheckbox = document.getElementById('selectAll');
    if (!selectAllCheckbox) return;
    
    const checkboxes = document.querySelectorAll('.task-checkbox');
    const checkedCount = selectedTasks.size;
    const totalCount = checkboxes.length;
    
    if (checkedCount === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    } else if (checkedCount === totalCount) {
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = false;
    } else {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = true;
    }
}

// 更新批量操作按钮
function updateBatchActionButton() {
    const batchActionBtn = document.getElementById('batchActionBtn');
    if (batchActionBtn) {
        batchActionBtn.disabled = selectedTasks.size === 0;
        
        const countSpan = batchActionBtn.querySelector('.selected-count');
        if (countSpan) {
            countSpan.textContent = selectedTasks.size;
        }
    }
}

// 更新任务计数
function updateTaskCount(total) {
    const countElement = document.getElementById('taskCount');
    if (countElement) {
        countElement.textContent = `共 ${total} 个任务`;
    }
}

// 更新分页
function updatePagination(pageData) {
    totalPages = pageData.totalPages;
    currentPage = pageData.number + 1; // Spring Boot分页从0开始
    
    const paginationInfo = document.getElementById('paginationInfo');
    if (paginationInfo) {
        const start = pageData.number * pageData.size + 1;
        const end = Math.min(start + pageData.size - 1, pageData.totalElements);
        paginationInfo.textContent = `显示 ${start}-${end} 条，共 ${pageData.totalElements} 条`;
    }
    
    const prevBtn = document.getElementById('prevPage');
    const nextBtn = document.getElementById('nextPage');
    
    if (prevBtn) {
        const prevItem = prevBtn.closest('.page-item');
        prevItem.classList.toggle('disabled', !pageData.hasPrevious);
    }
    
    if (nextBtn) {
        const nextItem = nextBtn.closest('.page-item');
        nextItem.classList.toggle('disabled', !pageData.hasNext);
    }
}

// 分页导航
function goToPage(page) {
    if (page < 1 || page > totalPages || page === currentPage || isLoading) return;
    
    currentPage = page;
    loadTasks();
}

// 查看任务详情
async function viewTask(taskId) {
    console.log('viewTask called with taskId:', taskId);
    console.log('bsComponents.taskDetailOffcanvas:', bsComponents.taskDetailOffcanvas);
    
    try {
        console.log('Fetching task details...');
        const response = await fetch(`/api/tasks/${taskId}`);
        if (!response.ok) throw new Error('获取任务详情失败');
        
        const task = await response.json();
        console.log('Task data received:', task);
        
        populateTaskDetail(task);
        
        if (bsComponents.taskDetailOffcanvas) {
            console.log('Showing offcanvas...');
            bsComponents.taskDetailOffcanvas.show();
        } else {
            console.error('taskDetailOffcanvas component not initialized!');
            showToast('详情面板初始化失败', 'error');
        }
        
    } catch (error) {
        console.error('获取任务详情失败:', error);
        showToast('获取任务详情失败', 'error');
    }
}

// 填充任务详情
function populateTaskDetail(task) {
    currentTaskId = task.id;
    
    // 更新标题
    const taskIdElement = document.getElementById('detailTaskId');
    const taskTitleElement = document.getElementById('detailTaskTitle');
    if (taskIdElement) {
        taskIdElement.textContent = `T${String(task.id).padStart(3, '0')}`;
    }
    if (taskTitleElement) {
        taskTitleElement.textContent = task.title;
    }
    
    // 填充基本信息字段
    const fields = {
        'detailStatus': task.status,
        'detailPriority': task.priority,
        'detailEstimatedHours': task.estimatedHours,
        'detailActualHours': task.actualHours,
        'detailProgress': task.progress,
        'detailDescription': task.description
    };
    
    Object.entries(fields).forEach(([fieldId, value]) => {
        const field = document.getElementById(fieldId);
        if (field && value !== null && value !== undefined) {
            field.value = value;
        }
    });
    
    // 填充负责人下拉框
    const assigneeSelect = document.getElementById('detailAssignee');
    if (assigneeSelect) {
        // 清空现有选项
        assigneeSelect.innerHTML = '<option value="">未分配</option>';
        
        // 如果有负责人信息，添加当前负责人选项
        if (task.assigneeName) {
            const option = document.createElement('option');
            option.value = task.assigneeId || '';
            option.textContent = task.assigneeName;
            option.selected = true;
            assigneeSelect.appendChild(option);
        }
    }
    
    // 填充需求信息
    const requirementSelect = document.getElementById('detailRequirement');
    if (requirementSelect) {
        requirementSelect.innerHTML = '<option value="">无关联需求</option>';
        
        if (task.requirementTitle) {
            const option = document.createElement('option');
            option.value = task.requirementId || '';
            option.textContent = task.requirementTitle;
            option.selected = true;
            requirementSelect.appendChild(option);
        }
    }
    
    // 显示创建时间和更新时间
    const createdAtElement = document.getElementById('detailCreatedAt');
    const updatedAtElement = document.getElementById('detailUpdatedAt');
    if (createdAtElement && task.createdAt) {
        createdAtElement.value = new Date(task.createdAt).toLocaleString('zh-CN');
    }
    if (updatedAtElement && task.updatedAt) {
        updatedAtElement.value = new Date(task.updatedAt).toLocaleString('zh-CN');
    }
    
    // 显示进度
    const progressElement = document.getElementById('detailProgress');
    if (progressElement) {
        progressElement.value = task.progress || 0;
    }
    
    // 加载子任务
    loadSubtasks(task.id);
}

// 加载子任务列表
async function loadSubtasks(taskId) {
    try {
        const response = await fetch(`/api/tasks/${taskId}/subtasks`);
        if (!response.ok) {
            throw new Error('获取子任务失败');
        }
        
        const subtasks = await response.json();
        renderSubtasks(subtasks);
        
    } catch (error) {
        console.error('加载子任务失败:', error);
        renderSubtasks([]);
    }
}

// 渲染子任务列表
function renderSubtasks(subtasks) {
    const subtasksList = document.getElementById('subtasksList');
    const subtaskCount = document.getElementById('subtaskCount');
    
    if (subtaskCount) {
        subtaskCount.textContent = subtasks.length;
    }
    
    if (!subtasksList) return;
    
    if (subtasks.length === 0) {
        subtasksList.innerHTML = `
            <div class="text-center py-4 text-muted">
                <i class="bi bi-list-ul fs-3 d-block mb-2"></i>
                <p class="mb-0">暂无子任务</p>
            </div>
        `;
        return;
    }
    
    subtasksList.innerHTML = subtasks.map(subtask => `
        <div class="list-group-item d-flex justify-content-between align-items-center">
            <div class="flex-grow-1">
                <div class="d-flex align-items-center mb-1">
                    <span class="badge ${getStatusBadgeClass(subtask.status)} me-2">
                        ${getStatusText(subtask.status)}
                    </span>
                    <strong>T${String(subtask.id).padStart(3, '0')}</strong>
                </div>
                <div class="text-truncate" title="${escapeHtml(subtask.title)}">
                    ${escapeHtml(subtask.title)}
                </div>
                <small class="text-muted">
                    ${subtask.assigneeId ? getDeveloperDisplayName(subtask.assigneeId) : '未分配'} • 
                    ${subtask.estimatedHours || 0}h
                </small>
            </div>
            <div class="btn-group btn-group-sm">
                <button type="button" class="btn btn-outline-primary" 
                        onclick="viewTask(${subtask.id})" title="查看详情">
                    <i class="bi bi-eye"></i>
                </button>
                <button type="button" class="btn btn-outline-secondary" 
                        onclick="editTask(${subtask.id})" title="编辑">
                    <i class="bi bi-pencil"></i>
                </button>
            </div>
        </div>
    `).join('');
}

// 打开任务模态框
function openTaskOffcanvas(taskId = null) {
    currentTaskId = taskId;
    
    const offcanvasTitle = document.querySelector('#taskEditOffcanvas .offcanvas-title span');
    const offcanvasIcon = document.querySelector('#taskEditOffcanvas .offcanvas-title i');
    
    if (offcanvasTitle) {
        offcanvasTitle.textContent = taskId ? '编辑任务' : '新建任务';
    }
    if (offcanvasIcon) {
        offcanvasIcon.className = taskId ? 'bi bi-pencil-square me-2' : 'bi bi-plus-circle me-2 text-primary';
    }
    
    if (taskId) {
        loadTaskForEdit(taskId);
    } else {
        resetTaskForm();
    }
    
    if (bsComponents.taskEditOffcanvas) {
        bsComponents.taskEditOffcanvas.show();
    }
}

// 编辑任务
function editTask(taskId) {
    openTaskOffcanvas(taskId);
}

// 新建任务（保持向后兼容）
function openTaskModal(taskId = null) {
    openTaskOffcanvas(taskId);
}

// 加载任务用于编辑
async function loadTaskForEdit(taskId) {
    try {
        const response = await fetch(`/api/tasks/${taskId}`);
        if (!response.ok) throw new Error('获取任务信息失败');
        
        const task = await response.json();
        populateTaskForm(task);
        
    } catch (error) {
        console.error('获取任务信息失败:', error);
        showToast('获取任务信息失败', 'error');
    }
}

// 填充任务表单
function populateTaskForm(task) {
    const fields = {
        'taskTitle': task.title,
        'taskParentId': task.parentId,
        'taskRequirement': task.requirementId,
        'taskStatus': task.status,
        'taskPriority': task.priority,
        'taskAssignee': task.assigneeId,
        'taskEstimatedHours': task.estimatedHours,
        'taskActualHours': task.actualHours,
        'taskProgress': task.progress,
        'taskDescription': task.description
    };
    
    Object.entries(fields).forEach(([fieldId, value]) => {
        const field = document.getElementById(fieldId);
        if (field && value !== null && value !== undefined) {
            field.value = value;
        }
    });
    
    // 根据任务状态设置进度输入框的状态
    const taskProgressInput = document.getElementById('taskProgress');
    if (taskProgressInput && task.status) {
        if (task.status === 'TODO' || task.status === 'COMPLETED') {
            taskProgressInput.disabled = true;
        } else {
            taskProgressInput.disabled = false;
        }
    }
}

// 重置任务表单
function resetTaskForm() {
    if (elements.taskForm) {
        elements.taskForm.reset();
    }
    
    // 重置时启用进度输入框，因为默认状态通常不是TODO或COMPLETED
    const taskProgressInput = document.getElementById('taskProgress');
    if (taskProgressInput) {
        taskProgressInput.disabled = false;
        taskProgressInput.value = 0; // 设置默认进度为0
    }
}

// 获取任务表单数据
function getTaskFormData() {
    const getElementValue = (id) => {
        const element = document.getElementById(id);
        return element ? element.value : '';
    };
    
    const parentId = getElementValue('taskParentId') || null;
    
    // 根据parentId自动推断任务层级
    let level = 'LEVEL_1'; // 默认为主任务
    if (parentId) {
        // 如果有父任务，需要根据父任务层级推断
        // 这里简化处理，假设有父任务就是二级任务
        // 实际应用中可能需要查询父任务的层级
        level = 'LEVEL_2';
    }
    
    return {
        taskId: currentTaskId,
        title: getElementValue('taskTitle').trim(),
        parentTaskId: parentId,
        requirementId: getElementValue('taskRequirement') || null,
        status: getElementValue('taskStatus'),
        priority: getElementValue('taskPriority'),
        level: level,
        assigneeId: getElementValue('taskAssignee') || null,
        estimatedHours: parseFloat(getElementValue('taskEstimatedHours')) || null,
        actualHours: parseFloat(getElementValue('taskActualHours')) || null,
        progress: parseInt(getElementValue('taskProgress')) || 0,
        description: getElementValue('taskDescription').trim()
    };
}

// 处理任务表单提交
async function handleTaskSubmit(e) {
    e.preventDefault();
    
    const taskData = getTaskFormData();
    
    // 客户端验证：检查状态和进度的一致性
    if (taskData.status === 'TODO' && taskData.progress !== 0) {
        showToast('TODO状态的任务进度必须为0%', 'error');
        return;
    }
    
    if (taskData.status === 'COMPLETED' && taskData.progress !== 100) {
        showToast('COMPLETED状态的任务进度必须为100%', 'error');
        return;
    }
    
    if (taskData.progress < 0 || taskData.progress > 100) {
        showToast('任务进度必须在0-100之间', 'error');
        return;
    }
    
    try {
        const url = currentTaskId ? `/api/tasks/${currentTaskId}` : '/api/tasks';
        const method = currentTaskId ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(taskData)
        });
        
        if (!response.ok) throw new Error('保存任务失败');
        
        showToast(currentTaskId ? '任务更新成功' : '任务创建成功', 'success');
        
        if (bsComponents.taskEditOffcanvas) {
            bsComponents.taskEditOffcanvas.hide();
        }
        
        loadTasks();
        
    } catch (error) {
        console.error('保存任务失败:', error);
        showToast('保存任务失败', 'error');
    }
}

// 删除任务
async function deleteTask(taskId) {
    if (!confirm('确定要删除这个任务吗？此操作不可撤销。')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/tasks/${taskId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) throw new Error('删除任务失败');
        
        showToast('任务删除成功', 'success');
        selectedTasks.delete(taskId);
        loadTasks();
        
    } catch (error) {
        console.error('删除任务失败:', error);
        showToast('删除任务失败', 'error');
    }
}

// 打开批量操作模态框
function openBatchModal() {
    if (selectedTasks.size === 0) {
        showToast('请先选择要操作的任务', 'warning');
        return;
    }
    
    const selectedCountElement = document.getElementById('selectedTaskCount');
    if (selectedCountElement) {
        selectedCountElement.textContent = selectedTasks.size;
    }
    
    // 隐藏批量表单
    const batchFormContainer = document.getElementById('batchFormContainer');
    if (batchFormContainer) {
        batchFormContainer.style.display = 'none';
    }
    
    if (bsComponents.batchModal) {
        bsComponents.batchModal.show();
    }
}

// 显示批量操作表单
function showBatchForm(action) {
    const batchFormContainer = document.getElementById('batchFormContainer');
    const batchFormTitle = document.getElementById('batchFormTitle');
    const batchActionInput = document.getElementById('batchAction');
    
    if (batchActionInput) {
        batchActionInput.value = action;
    }
    
    if (batchFormTitle) {
        const actionTexts = {
            'updateStatus': '批量更新状态',
            'updatePriority': '批量更新优先级',
            'updateAssignee': '批量分配任务',
            'delete': '批量删除任务'
        };
        batchFormTitle.textContent = actionTexts[action] || '批量操作';
    }
    
    // 显示对应的表单字段
    const formFields = document.querySelectorAll('.batch-form-field');
    formFields.forEach(field => {
        field.style.display = 'none';
    });
    
    const targetField = document.getElementById(`batch${action.charAt(0).toUpperCase() + action.slice(1)}Field`);
    if (targetField) {
        targetField.style.display = 'block';
    }
    
    if (batchFormContainer) {
        batchFormContainer.style.display = 'block';
    }
}

// 处理批量操作提交
async function handleBatchSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData(e.target);
    const action = formData.get('action');
    const value = formData.get('value');
    
    if (!action || selectedTasks.size === 0) {
        showToast('操作参数不完整', 'error');
        return;
    }
    
    try {
        const response = await fetch('/api/tasks/batch', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                taskIds: Array.from(selectedTasks),
                action: action,
                value: value
            })
        });
        
        if (!response.ok) throw new Error('批量操作失败');
        
        showToast('批量操作成功', 'success');
        
        if (bsComponents.batchModal) {
            bsComponents.batchModal.hide();
        }
        
        selectedTasks.clear();
        loadTasks();
        
    } catch (error) {
        console.error('批量操作失败:', error);
        showToast('批量操作失败', 'error');
    }
}

// 显示加载状态
function showLoading(show) {
    const loadingElement = document.getElementById('loadingIndicator');
    if (loadingElement) {
        loadingElement.style.display = show ? 'block' : 'none';
    }
    
    if (elements.taskTable) {
        elements.taskTable.classList.toggle('loading', show);
    }
}

// 显示提示消息
function showToast(message, type = 'info') {
    // 创建Toast元素
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    
    const toastId = 'toast-' + Date.now();
    const toastHtml = `
        <div id="${toastId}" class="toast align-items-center text-white bg-${type === 'error' ? 'danger' : type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'primary'}" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">
                    ${escapeHtml(message)}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        </div>
    `;
    
    toastContainer.insertAdjacentHTML('beforeend', toastHtml);
    
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, {
        autohide: true,
        delay: 3000
    });
    
    toast.show();
    
    // 自动移除
    toastElement.addEventListener('hidden.bs.toast', () => {
        toastElement.remove();
    });
}

// 创建Toast容器
function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '1055';
    document.body.appendChild(container);
    return container;
}

// HTML转义
function escapeHtml(text) {
    if (!text) return '';
    return text.replace(/[&<>"']/g, function(match) {
        return {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        }[match];
    });
}

// 重置筛选条件
function resetFilters() {
    const statusFilter = document.getElementById('statusFilter');
    const priorityFilter = document.getElementById('priorityFilter');
    const requirementFilter = document.getElementById('requirementFilter');
    const assigneeFilter = document.getElementById('assigneeFilter');
    const searchInput = document.getElementById('searchInput');
    
    if (statusFilter) statusFilter.value = '';
    if (priorityFilter) priorityFilter.value = '';
    if (requirementFilter) requirementFilter.value = '';
    if (assigneeFilter) assigneeFilter.value = '';
    if (searchInput) searchInput.value = '';
    
    // 重新加载任务列表
    loadTasks();
}

/**
 * 加载需求数据
 */
function loadRequirements() {
    fetch('/api/requirements')
        .then(response => response.json())
        .then(requirements => {
            allRequirements = requirements;
            // 填充需求映射表
            requirementsMap.clear();
            requirements.forEach(requirement => {
                requirementsMap.set(requirement.id, requirement.title);
            });
            updateRequirementOptions();
        })
        .catch(error => {
            console.error('加载需求列表失败:', error);
        });
}

/**
 * 异步加载需求数据
 */
function loadRequirementsAsync() {
    return fetch('/api/requirements')
        .then(response => response.json())
        .then(requirements => {
            allRequirements = requirements;
            // 填充需求映射表
            requirementsMap.clear();
            requirements.forEach(requirement => {
                requirementsMap.set(requirement.id, requirement.title);
            });
            updateRequirementOptions();
            return requirements;
        })
        .catch(error => {
            console.error('加载需求数据失败:', error);
            // 降级处理：使用空数组，避免页面崩溃
            allRequirements = [];
            requirementsMap.clear();
            updateRequirementOptions();
            showToast('需求数据加载失败，部分功能可能受限', 'warning');
            throw error;
        });
}

/**
 * 更新需求选项
 */
function updateRequirementOptions() {
    // 更新任务模态框中的需求选项
    const requirementSelect = document.getElementById('taskRequirement');
    if (requirementSelect) {
        // 保留第一个选项
        const firstOption = requirementSelect.firstElementChild;
        requirementSelect.innerHTML = '';
        requirementSelect.appendChild(firstOption);
        
        allRequirements.forEach(requirement => {
            const option = document.createElement('option');
            option.value = requirement.id;
            option.textContent = requirement.title;
            requirementSelect.appendChild(option);
        });
    }
    
    // 更新筛选面板中的需求选项
    const requirementFilter = document.getElementById('requirementFilter');
    if (requirementFilter) {
        // 保留第一个选项
        const firstOption = requirementFilter.firstElementChild;
        requirementFilter.innerHTML = '';
        requirementFilter.appendChild(firstOption);
        
        allRequirements.forEach(requirement => {
            const option = document.createElement('option');
            option.value = requirement.id;
            option.textContent = requirement.title;
            requirementFilter.appendChild(option);
        });
    }
}

/**
 * 加载开发者数据
 */
function loadDevelopers() {
    fetch('/api/developers')
        .then(response => response.json())
        .then(developers => {
            allDevelopers = developers;
            updateDeveloperOptions();
        })
        .catch(error => {
            console.error('加载开发者列表失败:', error);
        });
}

/**
 * 异步加载开发者数据
 */
function loadDevelopersAsync() {
    return fetch('/api/developers')
        .then(response => response.json())
        .then(developers => {
            allDevelopers = developers;
            updateDeveloperOptions();
            return developers;
        })
        .catch(error => {
            console.error('加载开发者数据失败:', error);
            // 降级处理：使用空数组，避免页面崩溃
            allDevelopers = [];
            updateDeveloperOptions();
            showToast('开发者数据加载失败，部分功能可能受限', 'warning');
            throw error;
        });
}

/**
 * 更新开发者选项
 */
function updateDeveloperOptions() {
    // 更新任务模态框中的负责人选项
    const assigneeSelect = document.getElementById('taskAssignee');
    if (assigneeSelect) {
        // 保留第一个选项
        const firstOption = assigneeSelect.firstElementChild;
        assigneeSelect.innerHTML = '';
        assigneeSelect.appendChild(firstOption);
        
        allDevelopers.forEach(developer => {
            const option = document.createElement('option');
            option.value = developer.id;
            option.textContent = developer.name;
            assigneeSelect.appendChild(option);
        });
    }
    
    // 更新筛选面板中的负责人选项
    const assigneeFilter = document.getElementById('assigneeFilter');
    if (assigneeFilter) {
        // 保留第一个选项
        const firstOption = assigneeFilter.firstElementChild;
        assigneeFilter.innerHTML = '';
        assigneeFilter.appendChild(firstOption);
        
        allDevelopers.forEach(developer => {
            const option = document.createElement('option');
            option.value = developer.id;
            option.textContent = developer.name;
            assigneeFilter.appendChild(option);
        });
    }
    
    // 更新任务详情中的负责人选项
    const detailAssignee = document.getElementById('detailAssignee');
    if (detailAssignee) {
        // 保留第一个选项
        const firstOption = detailAssignee.firstElementChild;
        detailAssignee.innerHTML = '';
        detailAssignee.appendChild(firstOption);
        
        allDevelopers.forEach(developer => {
            const option = document.createElement('option');
            option.value = developer.id;
            option.textContent = developer.name;
            detailAssignee.appendChild(option);
        });
    }
}

/**
 * 获取需求显示名称
 */
function getRequirementDisplayName(requirementId) {
    return requirementsMap.get(parseInt(requirementId)) || '未知需求';
}

/**
 * 获取开发者显示名称
 */
function getDeveloperDisplayName(developerId) {
    const developer = allDevelopers.find(dev => dev.id === developerId);
    return developer ? developer.name : '未知开发者';
}





// 导出函数供HTML调用
window.taskManagement = {
    goToPage,
    viewTask,
    editTask,
    deleteTask,
    openTaskModal,
    openBatchModal,
    showBatchForm
};